package graduate.cslg.com.universityshopping;

import android.app.ProgressDialog;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;

import java.io.File;

import de.hdodenhof.circleimageview.CircleImageView;
import graduate.cslg.com.universityshopping.net.RegisterResponse;
import graduate.cslg.com.universityshopping.net.RetrofitDevelop;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.http.HEAD;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class RegisterActivity extends TakePhotoActivity implements View.OnClickListener {

    private EditText userAccount;
    private EditText userPass;
    private EditText userTel;
    private EditText userName;
    private Button registerButton;
    private CircleImageView mImageView;
    private ImageView backButton;
    private String getName, getPass, getTel, getAccount;
    private RegisterResponse mResponse;
    private String path;
    private MultipartBody.Part photo;

    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        userAccount = findViewById(R.id.get_user_account);
        userName = findViewById(R.id.get_user_name);
        userPass = findViewById(R.id.get_user_pass);
        userTel = findViewById(R.id.get_user_tel);
        registerButton = findViewById(R.id.button_register);
        backButton = findViewById(R.id.back_button);
        backButton.setOnClickListener(this);

        mImageView = findViewById(R.id.user_head_img);
        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAccount = userAccount.getText().toString();
                getPass = userPass.getText().toString();
                getTel = userTel.getText().toString();
                getName = userName.getText().toString();
                if (getAccount.length() == 9 && getPass.length() == 6 && getTel.length() == 11 && getName.length() > 0) {
                    showProgressDialog();
                    infoSubmit(getAccount, getPass, getTel, getName);
                } else {
                    Toast.makeText(RegisterActivity.this, "请输入正确的注册信息！", Toast.LENGTH_SHORT).show();
                }
            }
        });
        mImageView.setOnClickListener(this);
    }

    private void infoSubmit(String getAccount, String getPass, String getTel, String getName) {
        File file = new File(path);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photo = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        RetrofitDevelop.getAccountService()
                .RegisterCheck(getAccount, getPass, getTel, getName, photo, 2)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RegisterResponse>() {
                    @Override
                    public void onCompleted() {
                        if (mResponse.getStatus().equals("true")) {
                            Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Toast.makeText(RegisterActivity.this, "注册失败，请检查输入信息是否正确", Toast.LENGTH_SHORT).show();
                        }
                        closeProgressDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(RegisterActivity.this, "网络异常，请稍后再试", Toast.LENGTH_SHORT).show();
                        closeProgressDialog();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(RegisterResponse registerResponse) {
                        mResponse = registerResponse;
                    }
                });
    }

    /**
     * 显示进度对话框
     */
    private void showProgressDialog(){
        if(progressDialog==null){
            progressDialog=new ProgressDialog(this);
            progressDialog.setMessage("用户注册中，请稍等");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }
    /**
     * 关闭进度对话框
     */
    private void closeProgressDialog(){
        if(progressDialog!=null){
            progressDialog.dismiss();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_button:
                finish();
                break;
            case R.id.user_head_img:
                takePhoto(getTakePhoto());
                break;
        }
    }

    private void takePhoto(TakePhoto takePhoto) {
        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        Uri imageUri = Uri.fromFile(file);
        configCompress(takePhoto);
        configTakePhotoOption(takePhoto);
        takePhoto.onPickFromGalleryWithCrop(imageUri, getCropOptions());
    }

    private void configCompress(TakePhoto takePhoto) {
        int maxSize = 102400;
        int width = 800;
        int height = 800;
        boolean showProgressBar = true;
        boolean enableRawFile = true;
        //使用takePhoto自带的图片压缩工具
        CompressConfig config;
        config = new CompressConfig.Builder().setMaxSize(maxSize)
                .setMaxPixel(width >= height ? width : height)
                .enableReserveRaw(enableRawFile)
                .create();
        takePhoto.onEnableCompress(config, showProgressBar);
    }

    private void configTakePhotoOption(TakePhoto takePhoto) {
        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
        builder.setWithOwnGallery(true);
        builder.setCorrectImage(true);
        takePhoto.setTakePhotoOptions(builder.create());

    }

    @Override
    public void takeCancel() {
        super.takeCancel();
        Toast.makeText(this, "您取消了图像获取！", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        Toast.makeText(this, "获取照片成功", Toast.LENGTH_SHORT).show();
        Log.e("success",""+result.getImage().getOriginalPath().toString());
        path = result.getImage().getOriginalPath();
        Glide.with(this).load(path).into(mImageView);
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
        Toast.makeText(this, "获取照片失败！", Toast.LENGTH_SHORT).show();
    }

    /**
     * 图片裁剪参数设置方法
     * @return 图片裁剪工具
     */
    private CropOptions getCropOptions() {
        int height = 800;
        int width = 800;
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(width).setAspectY(height);
        builder.setWithOwnCrop(true);
        return builder.create();
    }
}
